<script setup lang="ts">
import { computed, ref } from "vue";
import { searchChatsRoomApi, joinChatsRoomApi } from "../api/chatsRoom";
import { getFriendsListApi, addFriendsApi } from "../api/friendsShip";
import { showDialog } from "vant";
import { useRouter } from "vue-router";

const router = useRouter();

const type = computed(() => router.currentRoute.value.params.type);

console.log("type", type.value);

const value = ref("");
const reason = ref("");

const show = ref(false);

const searchListGroup = ref<IConnectGroup[]>();
const searchListFriends = ref<IUser[]>();
const onSearch = (value: string) => {
  console.log("onSearch", value);
};

const joinGroup = async (id: number) => {
  await joinChatsRoomApi(id.toString());

  showDialog({
    title: "提示",
    message: "加入成功",
  });
};

const onClickLeft = async () => {
  router.back();
};

const onClickButton = async () => {
  if (type.value == "1") {
    const res = await searchChatsRoomApi(value.value);

    searchListGroup.value = res.data;
  }
  if (type.value == "0") {
    const res = await getFriendsListApi(value.value);
    searchListFriends.value = res.data;
  }
};

const currentUserId = ref();

const handleShow = (id: number) => {
  currentUserId.value = id;
  show.value = true;
};
const confirm = async () => {
  await addFriendsApi({
    toUserId: currentUserId.value,
    reason: reason.value,
  });

  showDialog({
    title: "提示",
    message: "请求已发送!",
  });
};
</script>

<template>
  <div class="search">
    <VanNavBar
      title="搜索"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <van-search
      v-model="value"
      show-action
      label="名称"
      placeholder="请输入搜索关键词"
      @search="onSearch"
    >
      <template #action>
        <div @click="onClickButton">搜索</div>
      </template>
    </van-search>

    <div class="search__res" v-if="type == '1'">
      <div v-for="item in searchListGroup" class="search__res-item">
        <div class="search__res-name">
          {{ item?.name }}
        </div>

        <div class="search__res-line" @click="joinGroup(item.id)">加入</div>
      </div>
    </div>
  </div>
  <div class="search__res" v-if="type == '0'">
    <div v-for="item in searchListFriends" class="search__res-item">
      <div class="search__res-name">
        {{ item.username }}
      </div>

      <div class="search__res-line" @click="handleShow(item.id)">添加</div>
    </div>

    <van-dialog
      v-model:show="show"
      title="添加好友"
      show-cancel-button
      @confirm="confirm"
    >
      <van-cell-group inset>
        <van-field v-model="reason" placeholder="请输入添加理由" />
      </van-cell-group>
    </van-dialog>
  </div>
</template>
